import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        car: { },
        logged: false,
        userInfo: {},
    },
    getters:{
        total(state){
            let shopTotal = {};
            for(let shopid in state.car){
                let sum =0;
                let tnum =0;
                for(let pid in state.car[shopid]){
                    let p = state.car[shopid][pid];
                   sum+=p.snum*p.price;
                   tnum+=p.snum;
                }

                shopTotal[shopid] = {sum:sum.toFixed(2),tnum:tnum};
            }
            return shopTotal
        }
    },
    mutations: {
        //初始化购物车
        initCar(state, shopid) {
            if (state.car[shopid] == undefined) {
                Vue.set(state.car, shopid, {})
            }
        },
        addCar(state, merchant) {
            let { shopid, merchInfo } = merchant;
            if (merchInfo.snum) {
                if (merchInfo.snum < merchInfo.store) {
                    merchInfo.snum++
                }
            } else {
                Vue.set(merchInfo, 'snum', 1)
            }
            Vue.set(state.car[shopid], merchInfo.id, merchInfo)
        },
        reduceCar(state, merchant) {
            let { shopid, merchInfo } = merchant;
            if (state.car[shopid][merchInfo.id].snum>0){
                state.car[shopid][merchInfo.id].snum--;
            }
            if (state.car[shopid][merchInfo.id].snum==0){
                Vue.delete(state.car[shopid],merchInfo.id)
            }   
        },
        setLogged(state, value) {
            state.logged = value;
        },
        setUserInfo(state, value) {
            state.userInfo = value;
        },
    },
});